package com.nuaa.shopping.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.nuaa.shopping.entity.User;

/*
 * 数据库模板工具类
 */
public class JdbcTemplate {

	/*
	 * 更新操作
	 */
	public static void update(String sql, Object... args) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = JdbcUtil.getConnection();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(null, ps, conn);
		}
	}

	/*
	 * 查询操作，返回一个集合
	 */
	public static <T> List<T> query(String sql, RowMapper<T> rm, Object... args) {
		List<T> list = new ArrayList<T>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtil.getConnection();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			rs = ps.executeQuery();
			while(rs.next()){
				list.add(rm.mapRow(rs));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(null, ps, conn);
		}
		return list;
	}
	
	/*
	 * 查询操作，返回单个对象
	 */
	public static <T> T queryForObject(String sql, RowMapper<T> rm, Object... args) {
		List<T> list = query(sql, rm, args);
		return list.size()>0 ? list.get(0) : null;
	}

	/**
	 * 保存操作
	 * @param sql
	 * @param args
	 * @return 返回生成的主键
	 */
	public static Integer save(String sql, Object... args) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = JdbcUtil.getConnection();
			ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); // 需要返回生成的主键
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			ps.executeUpdate();
			// 获取主键
			ResultSet rs = ps.getGeneratedKeys();
			if(rs.next()){
				return rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(null, ps, conn);
		}
		return null;
	}
}
